<?php

class yzzc_sunModuleFddRequest extends Core
{
    const HOST = 'https://uat-api.fadada.com/api/v5';

    const APPID = '00000838';
    const OPEN_CORP_ID = '4bfa09c4374b4a12a4cd27e70067a964';
    const APP_SECRET = 'IMUPNNTKPXV6SOD9V2LOGC0AHX6KW3TC';

    private static function commonHeader(): array
    {
        return [
            "X-FASC-App-Id"         => self::APPID,
            "X-FASC-Sign-Type"      => "HMAC-SHA256",
            "X-FASC-Timestamp"      => (int)(microtime(true) * 1000),
            "X-FASC-Nonce"          => uniqid("fdd"),
            "X-FASC-Grant-Type"     => "client_credential",
            "X-FASC-Api-SubVersion" => "5.1",
        ];
    }

    public static function send(string $path, array $data = [], string $method = 'POST')
    {
        $headers =  self::commonHeader();
        if ($data){
            $data = json_encode($data);
            $headers['X-FASC-AccessToken'] = self::getAccessToken();
            $headers['bizContent'] = $data;
            unset($headers['X-FASC-Grant-Type']);
        }

        ksort($headers);
        $sortParam = urldecode(http_build_query($headers));
        $signText = strtolower(hash("sha256", $sortParam));
        $hash = hash_hmac("sha256", $headers['X-FASC-Timestamp'], self::APP_SECRET, true);
        $sign = hash_hmac("sha256", $signText, $hash);
        $headers['X-FASC-Sign']  = $sign;
        $headers['Content-type'] = "application/x-www-form-urlencoded";

        unset($headers['bizContent']);
        $postHeader = self::headerHandle($headers);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, self::HOST . $path);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $postHeader);
        curl_setopt($ch, CURLOPT_POST, $method === "POST");
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        if($data){
            curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(['bizContent' => $data]));
        }
        $res = curl_exec($ch);
        curl_close($ch);

        $res = json_decode($res, true);

        if ($res['code'] != 100000) {
            throw new \Exception($res['msg']);
        }

        return $res;
    }

    private static function headerHandle(array $params): array
    {
        $result = [];
        foreach ($params as $k => $v) {
            $result[] = $k . ": " . $v;
        }
        return $result;
    }

    private static function getAccessToken()
    {
        $response = self::send('/service/get-access-token');
        return $response['data']['accessToken'];
    }
}